import React, { useState, useEffect } from 'react';
import { Table, Space, Button, message, Typography } from 'antd';
import { DownloadOutlined, DeleteOutlined, LinkOutlined } from '@ant-design/icons';
import * as api from '../../../services/api';
import FileUpload from '../../../components/filemanage/FileUpload';

const { Text } = Typography;

const FileManage = () => {
    const [files, setFiles] = useState([]);
    const [loading, setLoading] = useState(false);
    const [isAdmin, setIsAdmin] = useState(false);

    useEffect(() => {
        // 从 sessionStorage 获取用户信息，检查是否为管理员
        const user = JSON.parse(sessionStorage.getItem('user') || '{}');
        setIsAdmin(user.admin === 'yes');
    }, []);

    // 获取文件列表
    const fetchFiles = async () => {
        setLoading(true);
        try {
            const result = await api.getFileList();
            if (result.code === 200) {
                setFiles(result.data || []);
            } else {
                message.error('获取文件列表失败');
            }
        } catch (error) {
            message.error('获取文件列表失败');
        } finally {
            setLoading(false);
        }
    };

    // 首次加载时获取文件列表
    useEffect(() => {
        fetchFiles();
    }, []);

    // 处理文件下载
    const handleDownload = async (fileName) => {
        try {
            const response = await api.downloadFile(fileName);
            // 创建下载链接
            const url = window.URL.createObjectURL(new Blob([response]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', fileName);
            document.body.appendChild(link);
            link.click();
            link.remove();
            window.URL.revokeObjectURL(url);
            message.success('文件下载成功');
        } catch (error) {
            message.error('文件下载失败');
        }
    };

    // 处理文件删除
    const handleDelete = async (fileName) => {
        try {
            const result = await api.deleteFile(fileName);
            if (result.code === 200) {
                message.success('文件删除成功');
                fetchFiles(); // 重新获取文件列表
            }
        } catch (error) {
            message.error('文件删除失败');
        }
    };

    // 处理获取文件链接
    const handleGetUrl = async (fileName) => {
        try {
            const result = await api.getFileUrl(fileName);
            if (result.code === 200) {
                navigator.clipboard.writeText(result.data);
                message.success('文件链接已复制到剪贴板');
            }
        } catch (error) {
            message.error('获取文件链接失败');
        }
    };

    // 表格列定义
    const columns = [
        {
            title: '文件名',
            dataIndex: 'fileName',
            key: 'fileName',
        },
        {
            title: '大小',
            dataIndex: 'size',
            key: 'size',
            render: (size) => {
                const kb = size / 1024;
                if (kb < 1024) {
                    return `${kb.toFixed(2)} KB`;
                }
                const mb = kb / 1024;
                return `${mb.toFixed(2)} MB`;
            }
        },
        {
            title: '上传时间',
            dataIndex: 'uploadTime',
            key: 'uploadTime',
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button
                        type="link"
                        icon={<DownloadOutlined />}
                        onClick={() => handleDownload(record.fileName)}
                    >
                        下载
                    </Button>
                    <Button
                        type="link"
                        icon={<LinkOutlined />}
                        onClick={() => handleGetUrl(record.fileName)}
                    >
                        获取链接
                    </Button>
                    {isAdmin && (
                        <Button
                            type="link"
                            danger
                            icon={<DeleteOutlined />}
                            onClick={() => handleDelete(record.fileName)}
                        >
                            删除
                        </Button>
                    )}
                </Space>
            ),
        },
    ];

    return (
        <div className="file-manage">
            <div className="file-manage-header">
                <FileUpload onUploadSuccess={() => fetchFiles()} />
            </div>
            <Table
                columns={columns}
                dataSource={files}
                loading={loading}
                rowKey="fileName"
                pagination={{
                    defaultPageSize: 10,
                    showSizeChanger: true,
                    showTotal: (total) => (
                        <Text strong style={{ fontSize: '16px', color: '#1890ff' }}>
                            共 {total} 个文件
                        </Text>
                    )
                }}
            />
            <style jsx>{`
                .file-manage {
                    padding: 24px;
                }
                .file-manage-header {
                    margin-bottom: 16px;
                }
            `}</style>
        </div>
    );
};

export default FileManage; 